<?php
require_once "includes/config.php";
require_once "includes/functions.php";
require_once('AmazonAPI/.config.inc.php');
ob_start();
session_start();
$sessid=session_id();
ini_set('display_errors', 1); 
ini_set('error_reporting', 'E_error'); 
$msg = "";

$service = new AmazonAPI_FPS_Client(AWS_ACCESS_KEY_ID, 
                                       AWS_SECRET_ACCESS_KEY);
$request =  new AmazonAPI_FPS_Model_PayRequest();



/*function invokePay(AmazonAPI_FPS_Interface $service, $request) 
{
  try {
		  $response = $service->pay($request);
		  $payResult = $response->getPayResult();
		  $re_arr = array($payResult->getTransactionId(), $payResult->getTransactionStatus());
		  return $re_arr;		   

 } catch (AmazonAPI_FPS_Exception $ex) {
	 	  return "Failure";
 }
}*/

if(isset($_REQUEST['signature']) && !empty($_REQUEST['signature'])) {
	$tokenID = $_REQUEST['tokenID'];
	$callerReference = $_REQUEST['callerReference'];
	//print_r($_SESSION); exit;
									   
	$total_recipients = count($_SESSION['recipient_tokens']);
	$loop_limit = ($total_recipients - 1);
	for($i=0;$i<=$loop_limit;$i++){
		
		//echo $_SESSION['recipient_tokens'][$i]."<br />"; exit;
		
		$request->setCallerDescription('Swapen');
		$request->setCallerReference("swapen".rand());
		
		
		$request->setMarketplaceVariableFee('1.1');
		
		$request->setRecipientTokenId($_SESSION['recipient_tokens'][$i]);
		
		$request->setSenderTokenId($tokenID);//set the proper senderToken here.
		//$request->setChargeFeeTo('Caller');
		$amount = new AmazonAPI_FPS_Model_Amount();
		$amount->setCurrencyCode("USD");
		$amount->setValue($_SESSION['recipient_amounts'][$i]); //set the transaction amount here;
		
		$request->setTransactionAmount($amount);
		
	 	//object or array of parameters
	  	$return = invokePay($service, $request);
		//$return=true;
		
		if($return  && $return[2]!="Failure")
		{
			$today = date("Y-m-d");
			$bargaindeadline = mktime(0, 0, 0, date("m"), date("d")+700, date("y")); 
			$bargaindeadline=date("Y-m-d G:i:s", $bargaindeadline); 
			
			$sqlMsg = "SELECT * FROM tbl_messages WHERE messageid ='".$_SESSION['msg_id']."'";
			$recMsg = mysql_query($sqlMsg) or die(mysql_error());
			$rstMsg=mysql_fetch_array($recMsg);
			if(is_array($rstMsg))
			{
				$bargain_id=$rstMsg['bargain_id'];
	
				$sqlBar="select * from tbl_bargain tt  where tt.bargain_id ='".$bargain_id."'";
				$resBar=mysql_query($sqlBar);
				$rowBar=mysql_fetch_array($resBar);
				if(is_array($rowBar))
				{
					//insert item to tbl_items table....
					$sqlInsItem = "INSERT INTO tbl_items SET product_id='".$rstMsg['productid']."',seller_id='".$_SESSION['user_id_sess']."', owner_id=0,
					owner_type=0, price='".$rowBar['offer_amount']."', commission='".$rowBar['offer_commision']."', bargained='1', status='1',
					created_date='$today',bargain_duration='$bargaindeadline'";			
					$rstInsItem = mysql_query($sqlInsItem) or die(mysql_error());
					$item_id=mysql_insert_id();
					
					if(mysql_affected_rows()>0) 
					{
						$sqlUpdBar = "UPDATE tbl_messages SET is_buyed='1' WHERE messageid ='".$_SESSION['msg_id']."'";													 
						$rstUpdBar = mysql_query($sqlUpdBar) or die(mysql_error());
					}	
					
					$sqlPro="select * from tbl_wholeseller_product tt  where tt.product_id ='".$rstMsg['productid']."'";
					$resPro=mysql_query($sqlPro);
					$rowPro=mysql_fetch_array($resPro);
				
					$q = "INSERT INTO tbl_orders SET
							transaction_ID = '".$return[1]."',
							item_code = '',
							order_amount = '".$rowBar['offer_amount']."',
							transaction_status = '".$return[2]."',
							requestId = '".$return[3]."', 
							item_id = '".$item_id."',
							item_name = '".$rowPro['product_name']."',
							qty = '1',
							sales_tax='0',
							ordered_by = '".$_SESSION['user_id_sess']."',
							order_comm = '0',
							order_comm_to_user_id = '0',
							order_comm_by_user_id = '0',
							is_comm_paid = '0',
							verify_code='',
							isWhole='1',
							order_date = '".date('Y-m-d')."'";
					mysql_query($q);
				}
			}		
									
			$_SESSION['order_msg'] = "Your transaction is successfull";
			header("location:index.php?order");
		}
		else
		{
			header("location:index.php?order");
		}
	}
	//get users order status
	/*$oq = "SELECT * FROM tbl_orders WHERE ordered_by = '".$_SESSION['user_id_sess']."' AND order_date = '".date('Y-m-d')."'";
	$or = mysql_query($oq) or die(mysql_error($oq));
	$oc = mysql_num_rows($or);
	if($oc == 0){
		$_SESSION['cart_msg'] = "Your transaction is not successfull";
		header("location:index.php?cart");
	}else{
		if(empty($msg)){
			$_SESSION['order_msg'] = "Your transaction is successfull";		
		}else{
			$_SESSION['order_msg'] = $msg;
		}
		header("location:index.php?order");
	}*/
	
	//use the above token ID to pay
}
function invokePay(AmazonAPI_FPS_Interface $service, $request) 
  {
      try {
              $response = $service->pay($request);
			  //$res_arr = array();
			  if($response){
			  	$payResult = $response->getPayResult();
				//$PayResult = $response->getPayResult();
				$TransactionId = $payResult->getTransactionId();
				$TransactionStatus = $payResult->getTransactionStatus();
				$responseMetadata = $response->getResponseMetadata();
				$RequestId = $responseMetadata->getRequestId();
			  	$res_arr = array($PayResult,
								 $TransactionId,
								 $TransactionStatus,
								 $RequestId
				);
			  }
			  return $res_arr;
              
                

     } catch (AmazonAPI_FPS_Exception $ex) {
         echo("Caught Exception: " . $ex->getMessage() . "\n");
         echo("Response Status Code: " . $ex->getStatusCode() . "\n");
         echo("Error Code: " . $ex->getErrorCode() . "\n");
         echo("Error Type: " . $ex->getErrorType() . "\n");
         echo("Request ID: " . $ex->getRequestId() . "\n");
         echo("XML: " . $ex->getXML() . "\n");
		 return false;
     }
 }
?>